﻿using System.Text; 
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Linq;
using Wedo.Recognition.Domain.Models;
using Wedo.Recognition.Domain;
using Wedo.Recognition.Service;
using Wedo.Utility;
using Wedo.Recognition.Domain;
using Wedo.Mvc.Pager;
using System.IO;
using Wedo.Service.Common;
using Wedo.Recognition.Service.Service;
using Wedo.Recognition.Domain.ViewModels;
using Wedo.Recognition.Service.BankImport;
using Wedo.Domain.Models;
using System.Data.Objects;
using Wedo.Recognition.Repository;



namespace Wedo.Recognition.Service
{
    public class BankDataService : BaseService<BankData>
    {
        #region 基础
        public BankDataService(IUnitWork dbContext)
            : base(dbContext, dbContext.Set<BankData>())
        {

        }
 
        /// <summary>
        /// 添加新的账单记录
        /// </summary>
        /// <param name="item">账单记录</param>
        public bool CheckBankDataItemExists(string bankRemarkNum)
        {
            if (string.IsNullOrWhiteSpace(bankRemarkNum))
                throw new ArgumentNullException("不能添加空对象");
            if (_repository.All().Count(s => s.BankRemarkNum == bankRemarkNum) > 0)
                return true;
            return false;
        } 
        #endregion
         
        public override BankData Add(BankData entity)
        {
            int length = 6;
            entity.Assiginment = CreateAssiginment(GetMaxAssiginment(length), length);
            entity.Status = 1;
            entity.AccountDate = DateTime.Now;
            var bank = _dbContext.Set<Bank>().Find(m => m.BankCode == entity.BankCode);
            
            if (bank != null)
            {
                entity.Currency = bank.Currency;
            }
            return base.Add(entity);
        }

        #region 导入

        public List<IPBankData> GetImportBankData(string filePath, ImportType type)
        {
            List<IPBankData> list = new List<IPBankData>();
            Wedo.Utility.File.ObjectFromFile<IPBankData> file = null;

            switch (type)
            {
                case ImportType.SLBC:
                    {
                     var imp = new SLBCBankImport();
                     imp.Banks = _dbContext.Set<Bank>()
                         .Filter(m => m.BankName == "三菱银行").ToList();
                     imp.Params = _dbContext.Set<SysParam>().All().ToList();
                     file = imp;
                    }
                    break;
                case ImportType.PCBC_Telegraphic:
                    {
                        var imp = new PCBC_TelegraphicBankImport();
                        imp.Banks = _dbContext.Set<Bank>()
                            .Filter(m => m.BankName.Contains("中国银行")).ToList();
                        imp.Params = _dbContext.Set<SysParam>().All().ToList();
                        file = imp;

                    }
                    break;
                case ImportType.HSBC:
                    {
                        var imp = new HSBCBankImport();
                        imp.Banks = _dbContext.Set<Bank>()
                            .Filter(m => m.BankName == "汇丰银行").ToList();
                        imp.Params = _dbContext.Set<SysParam>().All().ToList();
                        file = imp;

                    }
                    break;
            }
            list = file.GenerateObjectsFromFile(type.ToString(), filePath).ToList();

            //ImportBankDataList(list);
            ImportIPBandData(list);
            return list;
        }

        /// <summary>
        /// 最大编号
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        private string GetMaxAssiginment(int length)
        {
            string today ='P'+ DateTime.Today.ToString("yyyyMMdd");
            string sql = " select max(Assiginment) from BankData where left(Assiginment,9)=@p0";
            return _dbContext.SqlQuery<string>(sql, today).FirstOrDefault();
        }

        //[HttpPost]
        //public void ImportData(List<BankData> list)
        //{
        //    if (list != null && list.Count > 0)
        //    {
        //        int length = 6;
        //        string lastNum = GetMaxAssiginment(length);
        //        list.ForEach(s =>
        //        {
        //            try
        //            {
        //                lastNum = CreateAssiginment(lastNum, length);
        //                s.Assiginment = lastNum;
        //                s.Status = 1;
        //                s.AccountDate = DateTime.Now;
        //                _set.Add(s);
        //                Commit();
        //            }
        //            catch { }
        //        });
        //    }
        //}

        public void ImportIPBandData(List<IPBankData> listData)
        {
            if (listData == null || listData.Count <= 0)
                return;
            string batchID = DateTime.Now.ToString("yyyyMMddhhmmss")+StringHelper.RandomString(5);
            listData.ForEach(s =>
            {
                s.BatchID = batchID;
                CheckIsExsit(s);
                try
                {
                    _dbContext.Set<IPBankData>().Create(s);
                    Commit();
                }
                catch (Exception e) { }
            });
        }

        public void SaveIPBankData(string batch,string user)
        {
            CustomerService cService = new CustomerService();
            var listData = _dbContext.Set<IPBankData>().Filter(m => m.BatchID == batch).ToList();
            if (listData == null || listData.Count <= 0)
                throw new Exception("没有需要保存的数据！");

            int length = 6;
            string lastNum = GetMaxAssiginment(length);

            listData.ForEach(s =>
            {
                lastNum = CreateAssiginment(lastNum, length);

                try
                {
                    BankData bd = new BankData
                    {
                        Id = s.Id,
                        Status = 1,
                        AccountDate = DateTime.Now,
                        Assiginment = lastNum,
                        BankCode = s.BankCode,
                        BankRemarkNum = s.BankRemarkNum,
                        BankPaidIn = s.BankPaidIn.GetValueOrDefault(0),
                        BankServiceFee = s.BankServiceFee,
                        Currency = s.Currency,
                        LCNumber = s.LCNumber,
                        Payer = s.Payer,
                        TradeAddionalComment = s.TradeAddionalComment,
                        ReceiveType = s.ReceiveType,
                        ReceiveDate = s.ReceiveDate.GetValueOrDefault(DateTime.Now),
                        CreatedBy=user,
                        ModifiedBy=user
                    };
                    var cust= cService.GetDefaultCustomer(s.Payer);
                    if (cust != null && cust.Length == 2)
                    {
                        bd.CustomerCode = cust[0];
                        bd.CustomerName = cust[1];
                    }
                    _repository.Create(bd);
                }
                catch (Exception e) { }

            });
            ClearBatch(batch);

            //EmailService email = new EmailService(_dbContext);
            //email.CreateImportNoticeEmail();
        }
 
        /// <summary>
        /// 检查是否重复存在
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private bool CheckIsExsit(IPBankData item)
        {
            var query = _repository.Filter(m => m.ReceiveDate == item.ReceiveDate 
                && m.Payer == item.Payer && m.BankPaidIn == item.BankPaidIn);
            if (string.IsNullOrWhiteSpace(item.BankRemarkNum))
            {
                item.HasExists = query.Count() > 0;
            }
            else
            {
                item.HasExists = query.Count(s => s.BankRemarkNum == item.BankRemarkNum.Trim()) > 0;
            }
            return item.HasExists;
        }

        /// <summary>
        /// 删除导入
        /// </summary>
        /// <param name="id"></param>
        public void DeleteIP(Guid id)
        {
            var model = _dbContext.Set<IPBankData>().Find(id);
           if (model != null)
           {
               _dbContext.Set<IPBankData>().Delete(model);
               Commit();
           }
        }

        public void ClearBatch(string batch)
        {
            if (batch.IsNotNullOrWhiteSpace())
            {
                string sql = "delete from IPBankData where BatchID=@p0 ";
                _dbContext.ExSql(sql, batch);
            }
        }

        public string ResolveBankData(string file, string user)
        {
            int updateCount = 0;
            int sumCount = 0;
            StringBuilder UnDealRecordsStr = new StringBuilder();
            CustomerService cService = new CustomerService();
            List<Dictionary<string, string>> records = LoadFile('\t', file);
            Dictionary<string, string> AnalyticbankDataMap = ExportMap.ExportMaps["BankData"];
            foreach (var record in records)
            {
                string CustomerCode = record[AnalyticbankDataMap["CustomerCode"]];
                if (CustomerCode.IsNullOrWhiteSpace())
                    continue;
                string Assiginment = record[AnalyticbankDataMap["Assiginment"]];
                string CustomerName = record[AnalyticbankDataMap["CustomerName"]];
                if (CustomerCode.IsNotNullOrWhiteSpace() && CustomerName.IsNullOrWhiteSpace())
                {
                    try
                    {
                        CustomerName = cService.GetCustomNameByCode(CustomerCode);
                    }
                    catch { }
                }
                sumCount++;
                BankData BankDataInfo = this.GetAll(s => s.Assiginment == Assiginment).FirstOrDefault();

                if (BankDataInfo != null)
                {
                    BankDataInfo.CustomerCode = CustomerCode;
                    BankDataInfo.CustomerName = CustomerName;
                    BankDataInfo.FinanceCheckOut = true;
                    BankDataInfo.FinanceCheckMan = user;
                    updateCount++;
                    Commit();

                }
                else
                {
                    UnDealRecordsStr.Append(string.Format("{0}; \n", Assiginment));
                }
            }
            return "导入数据" + sumCount + "条，成功" + updateCount + "条。" + UnDealRecordsStr.ToString();
        }

        #endregion


        #region 其他

        /// <summary>
        /// 删除签出
        /// </summary>
        /// <param name="id"></param>
        public void DeleteRecord(Guid id)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("delete from CheckRecord where ID='{0}';", id);
            builder.AppendFormat("delete from PaymentApply where CheckRecordID='{0}';", id);
            builder.AppendFormat("delete from RefundmentApply where CheckRecordID='{0};'", id);
            builder.AppendFormat("delete from ReleaseOrder where CheckRecordID='{0}';", id);
            _dbContext.ExSql(builder.ToString());
        }

        /// <summary>
        /// 财务同意放单
        /// </summary>
        /// <param name="?"></param>
        /// <param name="confirmMan"></param>
        public void ConfirmOrder(Guid id, string confirmMan)
        {
            var releaseOrder = _dbContext.Set<ReleaseOrder>().Find(id);

            if (releaseOrder.Status > 1)
                throw new System.Exception("已经审批，不能再审批");
            releaseOrder.Status = 2;
            releaseOrder.Approver = confirmMan;
            releaseOrder.Modified = DateTime.Now;

            Guid batch = Guid.NewGuid();
            releaseOrder.BatchID=batch;
            Commit();

            //EmailService email = new EmailService(_dbContext);
            //email.CreateConfirmOrderEmail(new List<ReleaseOrder> { releaseOrder }, batch,releaseOrder.ApplyMan);

        }

        /// <summary>
        /// 财务同意放单
        /// </summary>
        /// <param name="?"></param>
        /// <param name="confirmMan"></param>
        public void ConfirmOrders(List<Guid> ids, string confirmMan)
        {
            ids.CheckNull("请选择账单编号");

            var releaseOrders = _dbContext.Set<ReleaseOrder>()
                .Filter(s => ids.Any(m => m == s.Id)).ToList();

            foreach (var item in releaseOrders.GroupBy(m => m.ApplyMan))
            {
                Guid batch = Guid.NewGuid();
                foreach (var s in item)
                {
                    if (s.Status > 1)
                        continue;
                    s.Status = 2;
                    s.Approver = confirmMan;
                    s.Modified = DateTime.Now;
                    s.ApprovalTime = DateTime.Now;
                    s.BatchID = batch;
                }
                Commit();

                //EmailService email = new EmailService(_dbContext);
                //email.CreateConfirmOrderEmail(item.ToList(),batch,item.Key);
            }
        }


        /// <summary>
        /// 财务拒绝放单
        /// </summary>
        /// <param name="?"></param>
        /// <param name="confirmMan"></param>
        public void RejectOrders(List<Guid> ids, string confirmMan)
        {
            var releaseOrders = _dbContext.Set<ReleaseOrder>()
                .Filter(s => ids.Any(m => m == s.Id)).ToList();

            foreach (var item in releaseOrders.GroupBy(m => m.ApplyMan))
            {
                Guid batch = Guid.NewGuid();
                foreach (var s in item)
                {
                    if (s.Status > 1)
                        continue;
                    s.Status = 3;
                    s.Approver = confirmMan;
                    s.Modified = DateTime.Now;
                    s.ApprovalTime = DateTime.Now;
                    s.BatchID = batch;
                }
                Commit();

                //EmailService email = new EmailService(_dbContext);
                //email.CreateConfirmOrderEmail(item.ToList(),batch,item.Key);
            }
        }

        /// <summary>
        /// 拒绝放单
        /// </summary>
        /// <param name="?"></param>
        /// <param name="confirmMan"></param>
        public void RejectOrder(Guid id, string confirmMan)
        {
            //CheckIdValid(id, "银行账单编号");
            //CheckStringIsNullOrEmpty(confirmMan, "确认账单申请人");

            var releaseOrder = _dbContext.Set<ReleaseOrder>().Find(id);
            //CheckObjNull(releaseOrder, "账单数据");
            if (releaseOrder.Status > 1)
                throw new System.Exception("已经审批，不能再审批");
            Guid batch = Guid.NewGuid();
            releaseOrder.BatchID = batch;

            releaseOrder.Status = 3;
            releaseOrder.Approver = confirmMan;
            releaseOrder.Modified = DateTime.Now;

            Commit();
            //EmailService email = new EmailService(_dbContext);
            //email.CreateConfirmOrderEmail(new List<ReleaseOrder> { releaseOrder },batch,releaseOrder.ApplyMan);

        } 
        #endregion

        #region 操作

        public void UpdateDocumentNO(Guid id,string newDocumentNO)
        {
            newDocumentNO.CheckNull("新DocumentNo不能为空！");
            var model = GetById(id);
            if (model.ImportSAP == false)
                throw new Exception("还未导入SAP，没有DocumentNo");
            if (model.GenerateTransferVoucher == false)
                throw new Exception("还未生成转账凭证，不需要修改DocumentNo");

            if (model.DocumentNo != newDocumentNO)
            {
                model.DocumentNo = newDocumentNO;
                var tv = _dbContext.Set<TransferVoucher>()
                    .Find(m => m.Assiginment == model.Assiginment);
                
                if (tv!=null&& tv.NewDocumentNo != newDocumentNO)
                {
                    tv.NewDocumentNo = newDocumentNO;
                }
                Commit();
            }

        }

        public void DealSAP(Guid id, string CustomerCode, string CustomerName, string user)
        {
            BankData BankDataInfo = GetById(id);
            BankDataInfo.CustomerCode = CustomerCode;
            BankDataInfo.CustomerName = CustomerName;
            BankDataInfo.ImportSAP = true;
            BankDataInfo.ImportSAPUser = user;
            Commit();
        }

        public void UnLock(Guid id, string CurrentUserName)
        {
            var model = GetById(id);
            model.CheckNull();
            if (model.IsDelete)
                throw new Exception("账单被废除，如果继续操作请恢复！");

            if (model.Status == 2)
            {
                model.Status = 1;
                Commit();
            }
            else
            {
                throw new Exception("账单没有被锁定，不需解锁");
            }
        }

        /// <summary>
        /// 锁定账单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="CurrentUserName"></param>
        public void Lock(Guid id, string CurrentUserName)
        {
            var model = GetById(id);
            model.CheckNull();
            if (model.IsDelete)
                throw new Exception("账单被废除，如果继续操作请恢复！");

            if (model.IsCanLock())
            {
                model.Status = 2;
                Commit();
                //EmailService email = new EmailService(_dbContext);
                //email.CreateComplianceTeam(id.ToString());
            }
            else
            {
                throw new Exception("不能锁定。账单未生成收款凭证或已经被锁定或已成功导入SAP。");
            }
        }

        /// <summary>
        /// 签出银行账单数据,CSRq
        /// </summary>
        /// <param name="id">账单编号</param>
        /// <param name="checkMan">签出人</param>
        public void CheckIn(Guid id, string checkMan)
        {
            //CheckIdValid(id, "银行账单编号");
            //CheckStringIsNullOrEmpty(checkMan, "签出账单申请人");

            BankData model = GetById(id);
            if (model.IsDelete)
                throw new Exception("账单被废除，如果继续操作请恢复！");

            if (model.CheckRecord.Count > 0)
                throw new Exception("已经被签出，如果你想继续签出可以通过争议解决！");
            else
            {
                model.CheckRecord.Add(
                    new CheckRecord
                    {
                        CreatedBy = checkMan,
                        ApplyMan = checkMan,
                        ApplyTime = DateTime.Now,
                        BankDataId = model.Id,
                        BankData = model,
                        Assiginment = model.Assiginment
                    });
                Commit();
            }
        }

        /// <summary>
        /// 财务签出
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="user"></param>
        /// <param name="CustomerName"></param>
        /// <param name="CustomerCode"></param>
        public void FinanceCheck(List<Guid> ids, string user, string CustomerName, string CustomerCode)
        {
            if (CustomerCode.IsNullOrWhiteSpace())
                throw new Exception("请选择客户！");
            if (ids != null && ids.Count > 0)
            {
                var list = _repository.Filter(m => ids.Any(s => s == m.Id) && m.Status == 1).ToList();
                foreach (var item in list)
                {
                    if (item.IsCanFinanceCheck())
                    {
                        item.FinanceCheckMan = user;
                        item.FinanceCheckOut = true;

                        item.CustomerName = CustomerName;
                        item.CustomerCode = CustomerCode;
                    }
                }
                Commit();
            }
            else
            {
                throw new Exception("至少选择一个！");
            }
        }


        public PagedList<BankData> CheckSearch(CommonSearchModel where)
        {
            where = where ?? new CommonSearchModel();
            IQueryable<CheckRecord> query = _dbContext.Set<CheckRecord>()
                .Get(includeProperties:"BankData");
            if (where.ApplyMan.IsNotNullOrWhiteSpace())
            {
                query = query.Where(m => m.ApplyMan == where.ApplyMan);
            }

            if (where.StartTime != null)
            {
                DateTime Start = where.StartTime.Value;
                query = query.Where(m => m.ApplyTime > Start);
            }
            if (where.EndTime != null)
            {
                DateTime endTime = where.EndTime.Value.AddDays(1);
                query = query.Where(m => m.ApplyTime < endTime);
            }

            if (!string.IsNullOrWhiteSpace(where.Keyword))
            {
                query = query.Where(m => m.Assiginment.Contains(where.Keyword));
            }


            var list = query.OrderByDescending(m => m.ApplyTime).ToPagedList(where.Page, 10);

            return new PagedList<BankData>(list.Select(m => m.BankData),where.Page,10,list.TotalItemCount);
        }

        /// <summary>
        /// 撤销签出银行账单数据
        /// </summary>
        /// <param name="id">签出记录编号</param>
        /// <param name="checkMan">签出人</param>
        public void CancelCheckIn(Guid id, string checkMan)
        {
            BankData model = GetById(id);

            if (model.IsDelete)
                throw new Exception("账单被废除，如果继续操作请恢复！");
            
            //删除签出信息,签出记录，认款申请，退款申请，放单记录
            var myCheck = model.CheckRecord.FirstOrDefault(m => m.ApplyMan == checkMan);
            if (myCheck!=null)
            {
                DeleteRecord(myCheck.Id);
            }
            else
            {
                throw new Exception("未签出，不需要撤销签出");
            }
        }

        /// <summary>
        /// 废除账单
        /// </summary>
        /// <param name="id"></param>
        public override void Remove(object id)
        {
            var model = GetById(id);
            if (model.IsDelete)
                throw new Exception("已经被废除不需要再废除！");
            model.IsDelete = true;

            Commit();
        }


        /// <summary>
        /// 恢复被废除的账单
        /// </summary>
        /// <param name="id"></param>
        public void RestoreRemove(Guid id)
        {
            var model = GetById(id);
            if (model.IsDelete==false)
                throw new Exception("已经被恢复不需要再恢复！");
            model.IsDelete = false;

            Commit();
        }

        #endregion
 
        #region 查询

        public  PagedList<BankData> GetSearchPagedList(BankDataSearch where) {
            where = where ?? new BankDataSearch();

            IQueryable<BankData> query = GetQuery(where);
            var paged = query.OrderByDescending(m => m.AccountDate)
                .ThenByDescending(m => m.Status)
                .ToPagedList(where.Page, 10);
            return paged;
        }

        /// <summary>
        /// 查询报表
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public IQueryable<BankData> GetReportQuery(BankDataReportSearch where)
        {
            where = where ?? new BankDataReportSearch();
            //报表去除废除的账单
            var query = All().Where(m=>m.IsDelete==false);
            if (where.StartTime != null)
            {
                DateTime Start = where.StartTime.Value;
                query = query.Where(m => m.AccountDate > Start);
            }
            if (where.EndTime != null)
            {
                DateTime endTime = where.EndTime.Value.AddDays(1);
                query = query.Where(m => m.AccountDate < endTime);
            }

 
            if (where.IsRecognition.HasValue)
            {
                if (where.IsRecognition == true)
                {
                    query = query.Where(m => m.PaymentApply.Count > 0 ||m.FinanceCheckOut);
                }
                else
                {
                    query = query.Where(m => m.FinanceCheckOut == false && m.PaymentApply.Count == 0);
                }
            }

            if (where.IsDisputed.HasValue)
            {
                if (where.IsDisputed == true)
                {
                    query = query.Where(m => m.DisputeApply.Count > 0);
                }
                else
                {
                    query = query.Where(m => m.DisputeApply.Count == 0);
                }
            }

            if (where.IsInSap.HasValue)
            {
                query = query.Where(m => m.ImportSAP == where.IsInSap);
            }

            if (!string.IsNullOrWhiteSpace(where.Keyword))
            {
                query = query.Where(m => m.Payer.Contains(where.Keyword));
            }
            if (where.Assiginment.IsNotNullOrWhiteSpace())
            {
                query = query.Where(m => m.Assiginment.Contains(where.Assiginment));
            }

            return query;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public IQueryable<BankData> GetQuery(BankDataSearch where)
        {
            where = where ?? new BankDataSearch();
            var query = All();
            if (where.StartTime != null)
            {
                DateTime Start = where.StartTime.Value;
                query = query.Where(m => m.AccountDate > Start);
            }
            if (where.EndTime != null)
            {
                DateTime endTime = where.EndTime.Value.AddDays(1);
                query = query.Where(m => m.AccountDate < endTime);
            }
            #region 高级查询

            if (where.AdvancedSearch)
            {
                if (where.FinanceCheckOut != null)
                {
                    query = query.Where(m => m.FinanceCheckOut == where.FinanceCheckOut.Value);
                }

                if (where.Status != null)
                {
                    query = query.Where(m => m.Status == where.Status);
                }

                if (where.ImportSAP.HasValue)
                {
                    query = query.Where(m => m.ImportSAP == where.ImportSAP.Value);
                }

                if (where.TransferVoucher.HasValue)
                {
                    query = query.Where(m => m.GenerateTransferVoucher == where.TransferVoucher.Value);
                }

                if (where.RecieveVoucher.HasValue)
                {
                    query = query.Where(m => m.GenerateRecieveVoucher == where.RecieveVoucher.Value);
                }

                if (where.HasChecked.HasValue)
                {
                    if (where.HasChecked.Value)
                    {
                        query = query.Where(m => m.CheckRecord.Count>0);
                    }
                    else
                    {
                        query = query.Where(m => m.CheckRecord.Count == 0);
                    }
                }

                if (where.IsDelete.HasValue)
                {
                    query = query.Where(m => m.IsDelete == where.IsDelete.Value);
                }
            } 
            #endregion
            if (!string.IsNullOrWhiteSpace(where.Assiginment))
            {
                query = query.Where(m => m.Assiginment.Contains(where.Assiginment));
            }

            if (!string.IsNullOrWhiteSpace(where.Keyword))
            {
                query = query.Where(m => m.Payer.Contains(where.Keyword));
            }
            return query;
        }

        public IQueryable<BankData> MyCheckBankData(CommonSearchModel where)
        {
            where = where ?? new CommonSearchModel();
            var query = All();
            if (where.StartTime != null)
            {
                DateTime Start = where.StartTime.Value;
                query = query.Where(m => m.AccountDate > Start);
            }
            if (where.EndTime != null)
            {
                DateTime endTime = where.EndTime.Value.AddDays(1);
                query = query.Where(m => m.AccountDate < endTime);
            }

            if (where.ApplyMan.IsNotNullOrWhiteSpace())
            {
                query = query.Where(m =>
                    m.CheckRecord.Count(s => s.ApplyMan == where.ApplyMan) > 0
                    );
            }

            if (!string.IsNullOrWhiteSpace(where.Keyword))
            {
                query = query.Where(m => m.Payer.Contains(where.Keyword));
            }
            return query;

        }

        /// <summary>
        /// 财务签出
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public PagedList<BankData>  FinanceSearch(BankDataSearch where)
        {
            IQueryable<BankData> query = GetQuery(where).Where(m => m.FinanceCheckOut);
            return query.OrderByDescending(m => m.AccountDate).ToPagedList(where.Page, 10);

        }

        /// <summary>
        /// 解析文件
        /// </summary>
        /// <param name="filePath"></param>
        public void AnalyticData(string filePath, string userAD, out int updateCount, out int sumCount, out string UnDealRecords)
        {
            updateCount = 0;
            sumCount = 0;
            UnDealRecords = "";
            StringBuilder UnDealRecordsStr = new StringBuilder();
            try
            {
                CustomerService cService = new CustomerService();

                List<Dictionary<string, string>> records = LoadFile(',', filePath);
                Dictionary<string, string> AnalyticbankDataMap = ExportMap.ExportMaps["AnalyticBankData"];
                foreach (var record in records)
                {
                    string Assiginment = record[AnalyticbankDataMap["Assiginment"]].ToString();
                    string DocumentNo = record[AnalyticbankDataMap["DocumentNo"]].ToString();
                    string CustomerCode = "";
                    string CustomerName = "";
                    if (record.Keys.Count > 2)
                    {
                        CustomerCode = record[AnalyticbankDataMap["SAPCode"]].ToString();
                        if (CustomerCode.IsNotNullOrWhiteSpace())
                        {
                            try
                            {
                                CustomerName = cService.GetCustomNameByCode(CustomerCode);
                            }
                            catch { }
                        }
                    }
                    sumCount++;
                    BankData BankDataInfo = this.GetAll( s => s.Assiginment == Assiginment).FirstOrDefault();

                    if (BankDataInfo != null)
                    {
                        BankDataInfo.DocumentNo = DocumentNo;
                        if (CustomerCode.IsNotNullOrWhiteSpace())
                        {
                            BankDataInfo.CustomerCode = CustomerCode;
                        }
                        if (CustomerName.IsNotNullOrWhiteSpace())
                        {
                            BankDataInfo.CustomerName = CustomerName;
                        }
                        BankDataInfo.ImportSAP = true;
                        BankDataInfo.ImportSAPUser = userAD;
                        updateCount++;

                    }
                    else
                    {
                        UnDealRecordsStr.Append(string.Format("{0}; \n", Assiginment));
                    }

                }
                Commit();
                //没有更新的Assiginment记录
                UnDealRecords = UnDealRecordsStr.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 批量加载文件
        /// 最终返回的内容格式如:[ [{"名称":"小弟科技"},{"合同号":"23333"}],... ]
        /// </summary>
        /// <param name="sperator">文件分隔符</param>
        /// <param name="paths">文件路径数组</param>
        /// <returns>返回格式化后的文件内容</returns>
        public static List<Dictionary<string, string>> LoadFile(char sperator, string path)
        {
            if (string.IsNullOrEmpty(path) || !File.Exists(path))
                return null;

            List<Dictionary<string, string>> result = new List<Dictionary<string, string>>();
            var lines = File.ReadAllLines(path, Encoding.GetEncoding("gb2312"));// new StreamReader(stream, Encoding.GetEncoding("gb2312")))
            string[] header = lines[0].Split(new char[] { sperator }, StringSplitOptions.RemoveEmptyEntries);
            for (var i = 1; i < lines.Length; i++)
            {
                string[] record = lines[i].Split(sperator);
                if (record.Length == header.Length)
                {
                    Dictionary<string, string> dict = new Dictionary<string, string>();
                    for (int j = 0; j < header.Length; j++)
                    {
                        dict[header[j].Trim()] = record[j];
                    }
                    result.Add(dict);
                }

            }
            return result;
        }

        public List<BankData> GetReport(BankDataSearch where)
        {
            return  GetQuery(where).OrderBy(m => m.Assiginment).ToList(); 
        }
 
        #endregion

        #region 公共方法

        /// <summary>
        /// 为账单生成自动编号
        /// </summary>
        /// <param name="lastNum">最后的账单编号</param>
        /// <param name="length">日期后的长度</param>
        /// <returns></returns>
        public  string CreateAssiginment(string lastNum, int length)
        {
            string today = 'P' + DateTime.Today.ToString("yyyyMMdd");
            int lastCount = 0;
            //第一次添加或者当天第一次添加
            if (string.IsNullOrWhiteSpace(lastNum) || lastNum.StartsWith(today) == false)
            {
                lastCount = 0;
            }
            else
            {
                lastCount = Convert.ToInt32(lastNum.Substring(today.Length));
            }
            return string.Format("{0}{1}", today, (++lastCount).ToString().PadLeft(length, '0'));
        }

        ///// <summary>
        ///// 根据账单编号获取账单签出信息,如果不存在
        ///// </summary>
        ///// <param name="bandDataItemId">账单编号</param>
        ///// <returns>组装了签出记录的账单信息</returns>
        //public BankData GetById(Guid bandDataItemId)
        //{
        //    CheckIdValid(bandDataItemId, "账单编号");


        //    BankData item = _set.Find(bandDataItemId);
        //    if (item == null)
        //        throw new ArgumentNullException("账单数据不存在");
        //    item.CheckRecords = _dbContext.Set<CheckRecord>().Where(s => s.BankDataId == bandDataItemId).ToList();
        //    return item;
        //}

        ///// <summary>
        ///// 根据签出编号获取账单签出记录，不存在异常
        ///// </summary>
        ///// <param name="checkRecordId">账单签出记录ID</param>
        ///// <returns></returns>
        //public CheckRecord GetCheckRecordItem(Guid checkRecordId)
        //{
        //    CheckIdValid(checkRecordId, "账单签出记录编号");
        //    CheckRecord item = _dbContext.Set<CheckRecord>().Find(checkRecordId);
        //    if (item == null)
        //        throw new ArgumentNullException("账单签出记录不存在");
        //    return item;
        //}
        #endregion

    }
}
